package com.beiing.tianshuai.tianshuai.service;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.content.FileProvider;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.app.HttpRequestConstant;
import com.beiing.tianshuai.tianshuai.util.LogUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class UpdateAppService extends Service {

    public static final String DOWNLOAD_THREAD_NAME = "Download_Thread";

    private String mAppName;
    private String mUrl;
    private NotificationManager mNotificationManager;
    private Notification.Builder mBuilder;
    private boolean mIsStart;
    private int mFileLength;
    private File mApkFile;

    public UpdateAppService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {
            mAppName = intent.getStringExtra("app_name");
            mUrl = intent.getStringExtra("url");
            File dir = new File(Environment.getExternalStorageDirectory() + "/TianShuai/天率校园/");
            if (!dir.exists()) {
                if (dir.mkdirs()) {
                    LogUtils.i("创建路径 “/TianShuai/天率校园/” 成功", "make dir");
                } else {
                    LogUtils.e("创建路径 “/TianShuai/天率校园/” 失败", "make dir");
                }
            }
            createNotification();
        }
        return super.onStartCommand(intent, flags, startId);
    }

    /***
     * 创建通知栏
     */
    @SuppressLint("NewApi")
    public void createNotification() {
        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        mBuilder = new Notification.Builder(this);
        mBuilder.setContentTitle("正在下载安装包...")
                .setContentText("下载更新中")
                .setSmallIcon(R.drawable.logo_180);

        mIsStart = true;
        DownloadRunnable downloadRunnable = new DownloadRunnable();
        new Thread(downloadRunnable, DOWNLOAD_THREAD_NAME).start();
        startForeground(ID, mBuilder.build());
    }

    private class DownloadRunnable implements Runnable {

        @Override
        public void run() {
            if (mIsStart) {
                downloadFile();
            }
        }
    }

    private static final int UPDATE_WAITING = 0;
    private static final int UPDATE_PROGRESS = 1;
    private static final int DOWNLOAD_COMPLETE = 2;
    private static final int DOWNLOAD_FAILED = 3;
    private static final int ID = 12570;

    private Handler mHandler = new Handler(new Handler.Callback() {
        @SuppressLint("NewApi")
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case UPDATE_WAITING:
                    mBuilder.setContentText("waiting...")
                            .setProgress(0, 0, false);
                    mNotificationManager.notify(ID, mBuilder.build());
                    break;
                case UPDATE_PROGRESS:
                    double result = (((long) msg.obj) / (double) mFileLength) * 100;
                    mBuilder.setProgress(100, (int) result, false)
                            .setContentText((int) result + "%");
                    mNotificationManager.notify(ID, mBuilder.build());
                    break;
                case DOWNLOAD_COMPLETE:
                    mBuilder.setContentText("Download complete")
                            .setProgress(0, 0, false);
                    mNotificationManager.notify(ID, mBuilder.build());
                    mNotificationManager.cancel(ID);
                    stopForeground(true);
                    //判读版本是否在7.0以上
                    if (Build.VERSION.SDK_INT >= 24) {
                        updateMoreThan7();
                    } else {
                        updateUnderAndroid7();
                    }
                    mIsStart = false;
                    break;
                case DOWNLOAD_FAILED:
                    mBuilder.setContentText("Download failed")
                            .setProgress(0, 0, false);
                    mNotificationManager.notify(ID, mBuilder.build());
                    mNotificationManager.cancel(ID);
                    stopForeground(true);
                    mIsStart = false;
                    break;
                    default:break;
            }
            return false;
        }
    });

    private void downloadFile() {
        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        mHandler.sendMessage(mHandler.obtainMessage(UPDATE_WAITING));
        try {
            URL url = new URL(mUrl);
            LogUtils.i(HttpRequestConstant.REQUEST_DOWNLOAD_APK + mAppName, "apkURL");
            try {
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.connect();
                inputStream = conn.getInputStream();
                mFileLength = conn.getContentLength();
                String dirPath = Environment.getExternalStorageDirectory() + "/TianShuai/天率校园/";
                File apkDir = new File(dirPath);
                if (!apkDir.exists()) {
                    if (apkDir.mkdirs()) {
                        LogUtils.i("创建路径 “/TianShuai/天率校园/” 成功", "make dir");
                    } else {
                        LogUtils.e("创建路径 “/TianShuai/天率校园/” 失败", "make dir");
                    }
                }
                String path = dirPath + mAppName;
                mApkFile = new File(path);
                fileOutputStream = new FileOutputStream(mApkFile);
                int downloadCount = 0;
                int length;
                long progress = 0;
                byte[] bytes = new byte[2048];
                while ((length = inputStream.read(bytes)) != -1) {
                    fileOutputStream.write(bytes, 0, length);
                    progress += length;
                    fileOutputStream.flush();
                    if ((downloadCount == 0) || (int) (progress * 1000 / mFileLength) - 1 > downloadCount) {
                        downloadCount += 1;
                        mHandler.sendMessageDelayed(
                                mHandler.obtainMessage(UPDATE_PROGRESS, progress), 0
                        );
                    }
                }
                mHandler.sendMessage(mHandler.obtainMessage(DOWNLOAD_COMPLETE));
            } catch (IOException e) {
                e.printStackTrace();
                mHandler.sendMessage(mHandler.obtainMessage(DOWNLOAD_FAILED));
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fileOutputStream != null) {
                    try {
                        fileOutputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 适配Android7版本以下安装程序
     */
    private void updateUnderAndroid7() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(mApkFile),
                "application/vnd.android.package-archive");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    /**
     * 适配Android7版本以上安装程序
     */
    private void updateMoreThan7() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri apkURI = FileProvider.getUriForFile(this, "com.beiing.tianshuai.fileprovider", mApkFile);
        intent.setDataAndType(apkURI, "application/vnd.android.package-archive");
        // 由于没有在Activity环境下启动Activity,设置下面的标签
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //添加这一句表示对目标应用临时授权该Uri所代表的文件
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivity(intent);
    }
}
